package com.interf.wms;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.yy.base.util.SystemProperties;
import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionPool {
	private static String jdbcDriver = null; // 数据库驱动
	private static String url = null; // 数据 URL
	private static String userName = null; // 数据库用户名
	private static String password = null; // 数据库用户密码
	private static String testSql = null; // 测试连接是否可用的测试表名，默认没有测试表
	private static ComboPooledDataSource c3p0Source = null;
	private static int initCount = 3;
	private static int maxCount = 10;

	/**
	 * 获取数据库连接
	 */
	public static Connection getConnection() {
		try {
			if (c3p0Source == null) {
				createPool();
			}
			return c3p0Source.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 创建数据库连接池
	 */
	private static void createPool() {
		jdbcDriver = SystemProperties.getValue("db.jdbc.driverClassName");
		url = SystemProperties.getValue("db.jdbc.url");
		userName = SystemProperties.getValue("db.jdbc.username");
		password = SystemProperties.getValue("db.jdbc.password");
		testSql = SystemProperties.getValue("db.jdbc.testSql");

		String init = SystemProperties.getValue("db.jdbc.initCount");
		initCount = init == null ? 3 : Integer.parseInt(init);
		String max = SystemProperties.getValue("db.jdbc.maxCount");
		maxCount = max == null ? 10 : Integer.parseInt(max);

		try {
			c3p0Source = new ComboPooledDataSource();
			c3p0Source.setDriverClass(jdbcDriver);
			c3p0Source.setJdbcUrl(url);
			c3p0Source.setUser(userName);
			c3p0Source.setPassword(password);
			c3p0Source.setMaxPoolSize(maxCount);
			c3p0Source.setInitialPoolSize(initCount);
			//c3p0Source.setCheckoutTimeout(60);//设置连接超时验证60秒
		} catch (Exception e) {
			throw new RuntimeException("注册JDBC驱动程序异常：" + e.getMessage());
		}
	}

	public static void resetConnection(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}
	/**
	 * 销毁原有连接，建立新连接池
	 */
	public void resetPool() {
		c3p0Source.resetPoolManager();
	}

	public String getJdbcDriver() {
		return jdbcDriver;
	}
	public String getUrl() {
		return url;
	}
	public String getUserName() {
		return userName;
	}
	public String getPassword() {
		return password;
	}
	public String getTestSql() {
		return testSql;
	}
}